<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-total">
          全国设定地震个数
          <span>
            <i v-for="item in totalArr" :key="item">{{ item }}</i>
          </span>
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <!-- <subheadings :name="'各省（直辖市）设定地震个数统计'" /> -->
          <CollapsibleTable :name="'各省（直辖市）设定地震个数统计'" :tableData="earthquakeList" />
        </div>
        <div class="app-left-item">
          <subheadings :name="'自2020年以来破坏性地震验证情况统计'" />
          <earthquake :data="earthquakeSituationInfos" />
        </div>
        <div class="app-left-item">
          <subheadings :name="'设定地震个数增长趋势图'" />
          <ColumnLineChart :listData="earthquakeSetTrendData" />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'全国设定地震灾害损失分布图'" />
        <!-- 地图 -->
        <div class="app-map">
          <!-- 系统切换 -->
          <SystemSelect :styles="{ position: 'absolute', left: '42px' }" />
          <OlMap
            :doubleZoomDisable="true"
            :pinchZoomDisable="true"
            :refId="'disasterLosses'"
            style="height: 100%"
            @getMap="getMap"
            @mapClick="mapClick"
          ></OlMap>
          <CircleLegend
            style="position: absolute; left: 42px; bottom: 150px"
            :title="'图例'"
            :subTitle="mapData.legendData.legendSubTitle"
            :items="mapData.legendData.legendItems"
            :items-per-column="7"
          ></CircleLegend>
          <!-- <IndexMap></IndexMap> -->
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <LossAssessment :name="'设定地震灾害损失评估成果'" @searchFn="searchFn" />
        </div>
        <div class="app-right-item">
          <subheadings :name="'现场抽样复核情况'" />
          <ReviewSituation />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
import earthquake from './components/earthquake.vue';
import ColumnLineChart from './components/ColumnLineChart.vue';
import CollapsibleTable from './components/CollapsibleTable.vue';
import LossAssessment from './components/LossAssessment.vue';
import ReviewSituation from './components/ReviewSituation.vue';

import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Text } from 'ol/style';
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { ref, reactive, defineProps } from 'vue';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import CircleLegend from '@/components/CircleLegend';
import { disasterLossesLegendData, changeLegendData, findColorIndex } from '@/utils/disasterLossesLegendData';
import {
  getEarthquakeSetNum,
  getProvinceEarthquakeSet,
  getEarthquakeSituation,
  getEarthquakeSetTrend,
  // getSceneCheckSituation,
  getProvinceCoverage,
  // getCountyCoverage,
  getMapData,
} from '@/api/disasterLosess.js';
import { map } from 'echarts-gl';
import { getChinaBaseMap } from '@/map/projMap.js';

const data = reactive({
  earthquakeSetNum: '', //全国设定地震个数
  earthquakeList: [], //各省(直辖市)设定地震个数表
  earthquakeSituationInfos: {}, //自2015年以.subTitle坏性地震验证情况统计
  earthquakeSetTrendData: [], //设定地震个数增长趋势图
  // sceneCheckSituationInfos: {}, //现场抽样复核情况
  provinceCoverageData: [], //各省覆盖率
  // countyCoverage: '', //县覆盖率
});

const {
  earthquakeSetNum,
  earthquakeList,
  earthquakeSituationInfos,
  earthquakeSetTrendData,
  // sceneCheckSituationInfos,
  provinceCoverageData,
  // countyCoverage,
} = toRefs(data);
const mapData = reactive({
  searchData: {
    mm: 0,
    number: 0,
    result: 1,
    type: 0,
  },
  legendData: {
    legendSubTitle: '',
    legendItems: [],
    colors: [],
    legendColumn: 7,
    colorIndex: -1,
  },
});

const totalArr = ref([]);
getData();
// 获取页面数据
function getData() {
  // 全国设定地震个数
  getEarthquakeSetNum().then((res) => {
    earthquakeSetNum.value = res.data.earthquakeNum;
    totalArr.value = earthquakeSetNum.value ? Array.from(String(earthquakeSetNum.value)) : [];
  });

  // 各省(直辖市)设定地震个数表
  getProvinceEarthquakeSet().then((res) => {
    earthquakeList.value = res.data;
  });

  // 自2015年以来破坏性地震验证情况统计
  getEarthquakeSituation().then((res) => {
    console.log(res.data);
    earthquakeSituationInfos.value = res.data;
  });

  // 设定地震个数增长趋势图
  getEarthquakeSetTrend().then((res) => {
    earthquakeSetTrendData.value = res.data;
  });

  // 现场抽样复核情况
  // getSceneCheckSituation({ page: 1, rows: 10 }).then((res) => {
  //   sceneCheckSituationInfos.value = res.data;
  // });

  // 各省覆盖率
  getProvinceCoverage().then((res) => {
    provinceCoverageData.value = res.data;
  });

  // 县覆盖率
  // getCountyCoverage().then((res) => {
  //   countyCoverage.value = res.data;
  // });
}
// 更新查询条件
function searchFn(val) {
  // 查询时,需要格式化一下震级
  console.log(123456, val);
  // type:统计方式，result：评估结果，mm：震级（百分数），number：输入框
  mapData.searchData = val;
  const { subTitle, legendItems, colors } = changeLegendData(mapData.searchData);
  mapData.legendData.legendSubTitle = subTitle;
  mapData.legendData.legendItems = legendItems;
  mapData.legendData.colors = colors;
  if (mapInstance.value) {
    addMapData();
  }
}

const mapInstance = ref(null);
const vectorLayer = ref(null);
const overlayLayer = ref(null);
const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);

  addProvinceNameLayer();

  //   假数据
  createVectorLayer();
  createOverlayLayer();

  // addRandomPoints();
  addMapData();
};
function mapValue(value) {
  return ((value / 100) * 3 + 5).toFixed(1);
}
const addMapData = () => {
  if (vectorLayer.value?.getSource()) {
    vectorLayer.value.getSource().clear();
  }
  let params = {
    mm: mapValue(mapData.searchData.mm),
    number: mapData.searchData.number,
    result: mapData.searchData.result,
    type: mapData.searchData.type,
  };
  getMapData(params).then((res) => {
    console.log('----', res.data);
    let pointList = res.data;
    for (let i = 0; i < pointList.length; i++) {
      let item = pointList[i];
      const point = new Feature({
        geometry: new Point([item.longitude, item.latitude]),
      });
      const color = getColor(item);
      let style = null;
      if (color == disasterLossesLegendData.legendItems1[0].color || !color) {
        style = new Style({
          image: new CircleStyle({
            radius: 4,
            // fill: new Fill({ color }),
            stroke: new Stroke({ color: color, width: 0.3 }), // 取消边框
          }),
        });
      } else {
        style = new Style({
          image: new CircleStyle({
            radius: 4,
            fill: new Fill({ color }),
            stroke: null, // 取消边框
          }),
        });
      }
      point.setStyle(style);
      vectorLayer.value?.getSource().addFeature(point);
      points.push(point); // 将点标记添加到数组
    }
  });
  // });
};
const mapClick = (event) => {
  const clickedFeature = mapInstance.value.forEachFeatureAtPixel(event.pixel, (feature) => feature);
  return;
  console.log('click', clickedFeature);
  if (clickedFeature) {
    // 获取点击的省份边界
    const provinceGeometry = clickedFeature.getGeometry();

    // 移除或隐藏其他省份图层
    mapInstance.value.getLayers().forEach((layer) => {
      // if (layer !== provinceLayer.value) {
      if (layer.get('id') !== 'province') {
        // mapInstance.value.removeLayer(layer);
        layer.setVisible(false);
      } else {
        console.log('layer---', layer.getSource().getFeatures());
        layer
          .getSource()
          .getFeatures()
          .forEach((feature) => {
            console.log('-----', clickedFeature.get('name'), feature.get('name'));
            if (clickedFeature.get('name') !== feature.get('name')) {
              feature.setStyle(null);
            }
          });
      }
    });
    // 创建新的省份图层并添加到地图
    const newProvinceLayer = new VectorLayer({
      source: new VectorSource({
        features: [new Feature(provinceGeometry)],
      }),
      zIndex: 2,
      style: new Style({
        stroke: new Stroke({
          color: 'blue',
          width: 2,
        }),
        fill: new Fill({
          color: 'black',
        }),
      }),
    });
    mapInstance.value.addLayer(newProvinceLayer);
    // 计算放大后的视图范围
    const provinceExtent = provinceGeometry.getExtent();
    // 更新地图视图以显示具体的省份地图
    mapInstance.value.getView().fit(provinceExtent, { padding: [20, 20, 20, 20], duration: 1000 }); // 1000毫秒的动画效果
  }
};
function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 1,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#E1EFFF' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}

const createOverlayLayer = () => {
  overlayLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 9999,
  });
  mapInstance.value.addLayer(overlayLayer.value);
};
const createVectorLayer = () => {
  vectorLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 2,
  });
  mapInstance.value.addLayer(vectorLayer.value);
};
const points = []; // 存储点标记的数组
const changePoint = () => {
  if (!vectorLayer.value) {
    return;
  }
  if (points && points.length > 0) {
    const provinces = [
      { lonMin: 103.35, lonMax: 107.16, latMin: 28.0, latMax: 31.91 }, // 四川
      { lonMin: 93.5, lonMax: 99.12, latMin: 29.3, latMax: 31.9 }, // 西藏
    ];
    points.forEach((feature) => {
      // 修改点标记的属性或几何信息
      const province = provinces[Math.floor(Math.random() * provinces.length)];
      const lon = Math.random() * (province.lonMax - province.lonMin) + province.lonMin;
      const lat = Math.random() * (province.latMax - province.latMin) + province.latMin;
      const color = getRandomColor();
      feature.setGeometry(new Point([lon, lat]));
      feature.setStyle(
        new Style({
          image: new CircleStyle({
            radius: 4,
            fill: new Fill({ color }),
            stroke: null, // 取消边框
          }),
        })
      );
    });
  } else {
    addRandomPoints();
  }
  // 刷新图层
  vectorLayer.value.getSource().changed();
};
const addRandomPoints = () => {
  if (!vectorLayer.value) {
    return;
  }
  const provinces = [
    { lonMin: 103.35, lonMax: 107.16, latMin: 28.0, latMax: 31.91 }, // 四川
    { lonMin: 93.5, lonMax: 99.12, latMin: 29.3, latMax: 31.9 }, // 西藏
  ];

  for (let i = 0; i < 100; i++) {
    const province = provinces[Math.floor(Math.random() * provinces.length)];
    const lon = Math.random() * (province.lonMax - province.lonMin) + province.lonMin;
    const lat = Math.random() * (province.latMax - province.latMin) + province.latMin;
    const color = getRandomColor();

    const point = new Feature({
      geometry: new Point([lon, lat]),
    });

    const style = new Style({
      image: new CircleStyle({
        radius: 4,
        fill: new Fill({ color }),
        stroke: null, // 取消边框
      }),
    });

    point.setStyle(style);
    vectorLayer.value.getSource().addFeature(point);
    points.push(point); // 将点标记添加到数组
  }
};
const getRandomColor = () => {
  const colorPalette = mapData.legendData.colors;
  const randomIndex = Math.floor(Math.random() * colorPalette.length);
  return colorPalette[randomIndex];
};
const getColor = (item) => {
  const colorPalette = mapData.legendData.colors;
  const randomIndex = findColorIndex(mapData.legendData.legendItems, item.result);
  if (randomIndex < 0) {
    return colorPalette[0];
  }
  return colorPalette[randomIndex];
};
</script>

<style scoped lang="scss">
.app-main {
  display: flex;
  justify-content: space-between;

  .app-left {
    margin-left: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    &-total {
      width: 450px;
      height: 80px;
      background-size: 100% 100%;
      background-image: url('../../assets/images/losses/title.png');
      font-size: 22px;
      color: #46ffff;
      line-height: 80px;
      padding-left: 105px;
      box-sizing: border-box;
      display: flex;
      position: absolute;
      top: 100px;
      span {
        font-family: DS-Digital;
        font-weight: 600;
        font-size: 36px;
        padding-top: 22px;
        display: flex;
        margin-left: 8px;
        i {
          display: block;
          width: 20px;
          height: 36px;
          background: #004c86;
          margin: 0 2px;
          font-style: normal;
          line-height: 36px;
          text-align: center;
        }
      }
    }

    &-item {
      width: 450px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: absolute;
      z-index: 0;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
      }
      &:nth-child(2) {
        height: 220px;
        top: 180px;
        z-index: 10;
      }
      &:nth-child(3) {
        height: 300px;
        top: 418px;
      }
      &:nth-child(4) {
        height: 296px;
        top: 736px;
      }
    }
  }

  &-item {
    width: 450px;
    background: linear-gradient(135deg, rgba(0, 3, 45, 0.85) 0%, rgba(0, 12, 88, 0.85) 50%, rgba(0, 3, 45, 0.85) 100%);
    position: relative;
    position: absolute;
    &::after {
      content: '';
      display: block;
      width: 450px;
      height: 50px;
      background-size: 100% 100%;
      background-image: url('../../assets/images/common/bg_bottom.png') !important;
      position: absolute;
      bottom: -10px;
    }
    &:nth-child(2) {
      height: 220px;
      top: 200px;
      z-index: 10;
    }
    &:nth-child(3) {
      height: 300px;
      top: 430px;
    }
    &:nth-child(4) {
      height: 296px;
      top: 736px;
    }
  }
}

.app-map {
  width: 960px;
  height: 100%;
  //overflow: hidden; //test
  position: relative;
}
.app-right {
  margin-right: 30px;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: calc(100% - 40px);
  width: 450px;

  &-item {
    width: 450px;
    height: 470px;
    background: linear-gradient(135deg, rgba(0, 3, 45, 0.85) 0%, rgba(0, 12, 88, 0.85) 50%, rgba(0, 3, 45, 0.85) 100%);
    position: relative;
    &::after {
      content: '';
      display: block;
      width: 450px;
      height: 20px;
      background-size: 100% 100%;
      background-image: url('../../assets/images/common/bg_bottom.png') !important;
    }
    &:nth-child(2) {
      height: 455px;
    }
  }
}
</style>
